<?php
require_once "ByteBuffer.php";
class DataUtil{
	static function readInt8($buffer){
		$int8 = $buffer->getByte();
		return $int8;
	}
	static function readInt16($buffer){
		$int16 = $buffer->getByte()|($buffer->getByte()<<8);
		return $int16;
	}
	static function readInt32($buffer){
		$int32 = $buffer->getByte()|($buffer->getByte()<<8)|($buffer->getByte()<<16)|($buffer->getByte()<<24);
		return $int32;
	}
	static function readBytes($buffer,$len){
		$bytes = Array();
		for($i = 0; $i < $len; $i++){
			$bytes[] = $buffer->getByte();
		}
		return $bytes;
	}
	static function readBBin($buffer){
		$i8len = $buffer->getByte();
		return DataUtil::readBytes($buffer, $i8len);
	}
	static function readSBin($buffer){
		$i16len = DataUtil::readInt16($buffer);
		return DataUtil::readBytes($buffer, $i16len);
	}
	static function writeInt8($buffer, $int8){
		$buffer->putByte($int8);
	}
	static function writeInt16($buffer, $int16){
		$buffer->putByte($int16);
		$buffer->putByte($int16>>8);
	}
	static function writeInt32($buffer, $int32){
		$buffer->putByte($int32);
		$buffer->putByte($int32>>8);
		$buffer->putByte($int32>>16);
		$buffer->putByte($int32>>24);
	}
	static function writeBytes($buffer,$bin){
		if (is_array($bin)){
			foreach ($bin as $value){
				$buffer->putByte($value);
			}	
		}		
	}
	static function writeBBin($buffer, $bin){
		$i8 = count($bin);
		DataUtil::writeInt8($buffer,$i8);
		DataUtil::writeBytes($buffer,$bin);
	}
	static function writeSBin($buffer, $bin){
		$i16 = count($bin);
		DataUtil::writeInt16($buffer,$i16);
		DataUtil::writeBytes($buffer,$bin);
	}
	static function charFromHexChar($ch){
		if(strpos("0123456789") >= 0)return ord($ch)- 48;
		else return ord(strtolower($ch)) - 87;
	}
	static function decodeUrl($str){
		$rt = array();
		$len = strlen($str);
		for($i = 0; $i < $len; $i++){
			$ch = $str{$i};
			if($ch == "x"){
				$ch1 = $str{$i+1};
				$ch2 = $str{$i+2};
				$value = (self::charFromHexChar($ch1)<<4 | self::charFromHexChar($ch2))&0xFF;
				$rt[] = $value;
				$i+=2;
			}else if($ch == "+"){
				$rt[]= ord(' ');
			}else{
				$rt[] = ord($ch);
			}
		}
		return $rt;
	}
	static function decodeData($str){
		$len = strlen($str);
		$buf = ByteBuffer::allocate( $len ) ;
		for($i = 0; $i< $len; $i++){
			$value = ord($str{$i});
			$mul = 0;
			if($value <= 57){
				$mul = $value - 48;
				$value = ord($str{$i+1}); $i++; 
			}
			if($value >= 92)$value = $value - 97 + 26;
			else $value -= 65;
			$value += $mul*52;
			DataUtil::writeInt8( $buf , $value ) ;
		}
		return  $buf ->_array() ;
	}
}
?>